﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.Reflection;

namespace CommModule
{
    public class ObjectSerialization
    {


        public static byte[] SerializeObjectAsXml(Object obj)
        {
            String serializedString = SerializeObjectAsString(obj);

            UTF8Encoding encoding = new System.Text.UTF8Encoding();
            return encoding.GetBytes(serializedString);
        }

        public static String SerializeObjectAsString(Object obj)
        {
            MemoryStream memoryStream = new MemoryStream();
            StreamWriter streamWriter = new StreamWriter(memoryStream);

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Encoding = Encoding.UTF8;
            XmlWriter xmlWriter = XmlWriter.Create(streamWriter, settings);

            xmlWriter.WriteStartDocument();
            XmlSerializationUtils.GetConversionObjectXml(obj, xmlWriter);
            xmlWriter.WriteEndDocument();

            xmlWriter.Flush();
            xmlWriter.Close();

            StreamReader streamReader = new StreamReader(memoryStream);
            memoryStream.Position = 0;
            return streamReader.ReadToEnd();
        }

        public static Object DeserializeObjectFromXml(byte[] objBytes)
        {            
            UTF8Encoding enc = new UTF8Encoding();
            String xmlString = enc.GetString(objBytes);

            XmlTextReader xmlTextReader = new XmlTextReader(new StringReader(xmlString));
            xmlTextReader.Read();
            xmlTextReader.Read();

            if (xmlTextReader.IsEmptyElement)
                return null;
            else
                return XmlSerializationUtils.GetConversionXmlObject(xmlTextReader);
        }
    }
}
